<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 代理列表
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
                <el-select v-model="selectLevel.levelid" placeholder="代理等级" class="handle-select mr10">
                    <el-option label="所有等级" :value="0">所有等级</el-option>
                    <el-option v-for="item in levelData" :key="item" :label="item.levelname" :value="item.id"></el-option>
                </el-select>
                <el-input v-model="selectUsername.name" placeholder="用户名" class="handle-input mr10" clearable></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="danger" @click="deleteSearch" icon="el-icon-delete-solid">清空</el-button>
                <download-excel
                    class = "export-excel-wrapper"
                    :data = "tableData"
                    :fields = "json_fields"
                    name = "代理列表.xls">
                    <!-- 上面可以自定义自己的样式，还可以引用其他组件button -->
                    <!-- <el-button type="primary" size="small">导出EXCEL</el-button> -->
                    <el-button type="primary"><i class="el-icon-download"></i>导出Excel</el-button>
                </download-excel>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
				<el-table-column label="序号" type="index" show-overflow-tooltip width="50"></el-table-column>
                <el-table-column prop="name" label="用户名"></el-table-column>
				<el-table-column prop="tel" label="手机号"></el-table-column>
				<el-table-column prop="levelname" label="代理等级"></el-table-column>
                <el-table-column label="账户余额" width="100">
                    <template slot-scope="scope">￥{{scope.row.balance}}</template>
                </el-table-column>
				<el-table-column label="总收益" width="100">
				    <template slot-scope="scope">￥{{scope.row.total}}</template>
				</el-table-column>
                <el-table-column label="实名状态">
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.real_status===1?'success':'danger'"
                        >{{scope.row.real_status==1?'已实名':'未实名'}}</el-tag>
                    </template>
                </el-table-column>
				<el-table-column label="服务状态">
				    <template slot-scope="scope">
				        <el-tag
				            :type="scope.row.ser_status===0?'success':'danger'"
				        >{{scope.row.ser_status==0?'服务期':'已过期'}}</el-tag>
				    </template>
				</el-table-column>

                <el-table-column prop="regtime" label="注册时间"></el-table-column>
				<el-table-column prop="endtime" label="服务到期时间"></el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >续期</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="续期" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="选择日期">
					<el-date-picker
					      v-model="form.endtime"
					      type="datetime"
					      placeholder="选择日期时间"
						  format="yyyy-MM-dd HH:mm:ss"
						  value-format="yyyy-MM-dd HH:mm:ss">
					</el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getAgent } from '../../api/index';
import { updateAgent } from '../../api/index.js';
import { deleteOne } from '../../api/index.js';
import { getLevel } from '../../api/index.js';
import { selectLevel } from '../../api/index.js';
import { selectUsername} from '../../api/index.js';
import axios from 'axios';
import qs from 'qs';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                id : localStorage.getItem('id'),
                pageIndex: 1,
                pageSize: 5
            },
			selectLevel:{
				id:localStorage.getItem('id'),
				pageIndex :1,
				pageSize :10
			},
			selectUsername:{
				id:localStorage.getItem('id'),
				pageIndex:1,
				pageSize:10
			},
            tableData: [],
			levelData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            json_fields:{
                "用户名":"name",
                "手机号":"tel",
                "代理等级":"levelname",
                "账户余额":"balance",
                "总收益":"total",
                "注册时间":"regtime",
                "服务到期时间":"endtime"
            },
            json_meta: [
                [
                    {
                        " key ": " charset ",
                        " value ": " utf- 8 "
                    }
                ]
            ],
            ids:[]
        };
    },
    created() {
        this.getData();
    },
    methods: {
        deleteSearch(){
            this.selectUsername.name = '';
            this.getData();
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            getAgent(this.query).then(res => {
                console.log(res);
                this.tableData = res.t.list;
                this.pageTotal = res.t.total;
            });
			getLevel().then(res => {
				console.log(res);
				this.levelData = res.t;
			})
        },
        // 触发搜索按钮
        handleSearch() {
			// console.log(this.selectLevel);
			// this.query = {
			// 	levelid:this.selectLevel,
			// 	pageIndex: 1,
			// 	pageSize:10
			// };
			//console.log(this.query);
            //this.$set(this.query, 'pageIndex', 1);
            //this.getData();
			if(this.selectLevel.levelid != undefined){
                if(this.selectLevel.levelid == 0){
                    this.getData();
                }else{
                    selectLevel(this.selectLevel).then(res => {
                        console.log(res);
                        this.tableData = res.t.list;
                        this.pageTotal = res.t.total;
                    })
                }
			}
			if(this.selectUsername.name != undefined){
				selectUsername(this.selectUsername).then(res => {
					console.log(res);
					this.tableData = res.t.list;
					this.pageTotal = res.t.total;
				})
			}
        },
        // 删除操作
        handleDelete(index, row) {
			this.form = {id:row.id};
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
					deleteOne(this.form).then(res => {
						if(res.code == 200){
							this.$message.success('删除成功');
							this.tableData.splice(index, 1);
                            this.getData();
						}else{
							this.$message.error('删除失败');
							this.tableData.splice(index, 1);
						}
					});
                    
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            for(var i = 0; i < val.length; i++){
                this.ids[i] = val[i].id;
            }
            this.multipleSelection = this.ids;
            this.ids = [];
        },
        delAllSelection() {
            // const length = this.multipleSelection.length;
            // let str = '';
            // this.delList = this.delList.concat(this.multipleSelection);
            // for (let i = 0; i < length; i++) {
            //     str += this.multipleSelection[i].name + ' ';
            // }
            // this.$message.error(`删除了${str}`);
            // this.multipleSelection = [];
            axios.post('http://localhost:8080/agent/deleteSelect',qs.stringify(
                {ids:this.multipleSelection},
                {indices:false}
            )).then(res=>{
                if(res.data.code == 200){
                    this.$message.success('删除成功');
                    this.getData();
                }else{
                    this.$message.error('删除失败');
                }
            });
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = {id:row.id, endtime:row.endtime};
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
			updateAgent(this.form).then(res => {
				if(res.code == 200){
					this.$message.success(`修改第 ${this.idx + 1} 行成功`);
					this.getData();
				}else{
					this.$message.error(`修改第 ${this.idx + 1} 行失败`)
				}
			})
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.export-excel-wrapper {
    float: right;
}
</style>
